package com.lzp.customview.togglebtn

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.customview.widget.ViewDragHelper
import com.lzp.customview.R
import com.utils.SizeUtils

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 1/13/21
 */
class TwoButtonSeekBar : FrameLayout {

    private val TAG = "TwoButtonSeekBar"

    private val dp1 = SizeUtils.dip2px(context, 1)

    private var startProgress = 0f
    private var endProgress = 100f

    //进度条部分
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
    private var progressColor = Color.parseColor("#ffcfd7e2")
    private val progressLineHeight = dp1 * 2
    private var progressTopMargin = dp1 * 49f//进度条到顶部的距离

    //切换的图片
    private val leftIcon = View(context)
    private val rightIcon = View(context)
    private val toggleIconSize = dp1 * 28
    private var toggleImageRes = R.mipmap.pic_knob

    //起始点文字
    private val startText = TextView(context)
    private val endText = TextView(context)

    private val startAndEndTextColor = 0xff7c828c.toInt()
    private val currentTextColor = 0xff2c2d2e.toInt()

    private val textSize = 15f

    //起始点进度文字
    private val leftTextView = TextView(context)
    private val rightTextView = TextView(context)

    //左右进度
    private var leftProgress = 20f
    private var rightProgress = 50f

    private var progressWidth = 0

    private var leftX = 0
    private var rightX = 0

    private val dragHelper: ViewDragHelper = ViewDragHelper.create(this, DragHelperCallBack())

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initStartAndEndText()
        initLeftAndRightText()
        initLeftAndRightIcon()
    }

    init {
        progressPaint.style = Paint.Style.FILL
        progressPaint.color = progressColor
        progressPaint.strokeWidth = progressLineHeight.toFloat()
        progressPaint.style = Paint.Style.STROKE
        progressPaint.strokeCap = Paint.Cap.ROUND
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (progressWidth == 0 && w != 0) {
            progressWidth = w - toggleIconSize

            leftX = computeProgressX(leftProgress).toInt()
            rightX = computeProgressX(rightProgress).toInt()

            val leftLayout = leftIcon.layoutParams as LayoutParams
            leftLayout.leftMargin = leftX - toggleIconSize / 2
            val rightLayout = rightIcon.layoutParams as LayoutParams
            rightLayout.leftMargin = rightX - toggleIconSize / 2

            updateText(leftTextView, leftX.toFloat(), true)
            updateText(rightTextView, rightX.toFloat(), false)

        }
    }

    private fun updateText(textView: TextView, x: Float, isLeft: Boolean) {
        val xRate = (x - toggleIconSize / 2f) / progressWidth.toFloat()
        val totalProgress = endProgress - startProgress
        if (isLeft) {
            leftProgress = startProgress + totalProgress * xRate
        } else {
            rightProgress = startProgress + totalProgress * xRate
        }
        textView.text = (startProgress + totalProgress * xRate).toInt().toString()
        post {
            textView.translationX = x - textView.width / 2
        }
    }

    private fun computeProgressX(progress: Float): Float {
        val totalProgress = endProgress - startProgress
        val dProgressX = progressWidth / totalProgress
        return (progress - startProgress) * dProgressX + toggleIconSize / 2f
    }

    override fun dispatchDraw(canvas: Canvas?) {
        canvas?.let {
            progressPaint.color = progressColor
            canvas.drawLine(toggleIconSize / 2f, progressTopMargin, width - toggleIconSize / 2f, progressTopMargin, progressPaint)
            progressPaint.color = 0xff2c2d2e.toInt()
            it.drawLine(leftX.toFloat(), progressTopMargin, rightX.toFloat(), progressTopMargin, progressPaint)
        }
        super.dispatchDraw(canvas)
    }

    inner class DragHelperCallBack : ViewDragHelper.Callback() {
        override fun tryCaptureView(child: View, pointerId: Int): Boolean {
            return child == leftIcon || child == rightIcon
        }

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            var tempLeft = left
            if (left < 0) {
                tempLeft = 0
            } else if (left > width - toggleIconSize) {
                tempLeft = width - toggleIconSize
            }


            if (child == leftIcon) {
                if (tempLeft + toggleIconSize > rightIcon.left) {
                    tempLeft = rightIcon.left - toggleIconSize
                    leftX = rightIcon.left - toggleIconSize / 2
                } else {
                    leftX = tempLeft + toggleIconSize / 2
                }
                updateText(leftTextView, leftX.toFloat(), true)
            } else {
                if (tempLeft < leftIcon.right) {
                    rightX = leftIcon.right + toggleIconSize / 2
                    tempLeft = leftIcon.right
                } else {
                    rightX = tempLeft + toggleIconSize / 2
                }
                updateText(rightTextView, rightX.toFloat(), false)
            }
            invalidate()
            return tempLeft
        }

        override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
            return (progressTopMargin - toggleIconSize / 2f).toInt()
        }

        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            //停止滚动之后
        }
    }

    private fun initLeftAndRightIcon() {
        val iconTopMargin = (progressTopMargin - toggleIconSize / 2f).toInt()
        //开始进度
        val leftLayout = LayoutParams(toggleIconSize, toggleIconSize)
        leftLayout.topMargin = iconTopMargin
        leftLayout.bottomMargin = 5
        leftIcon.layoutParams = leftLayout
        leftIcon.setBackgroundResource(R.drawable.dot_fff)
        leftIcon.elevation = 5f


        //结束进度
        val rightLayout = LayoutParams(toggleIconSize, toggleIconSize)
        rightLayout.topMargin = iconTopMargin
        rightLayout.rightMargin = 5
        rightIcon.layoutParams = rightLayout
        rightIcon.setBackgroundResource(R.drawable.dot_fff)
        rightIcon.elevation = 5f

        addView(leftIcon)
        addView(rightIcon)
    }

    /**
     * 初始化左右进度显示的文字
     */
    private fun initLeftAndRightText() {
        leftTextView.setTextColor(currentTextColor)
        leftTextView.textSize = textSize
        leftTextView.text = leftProgress.toString()
        //宽度写大一点，免得每次文字修改都测量
        leftTextView.layoutParams = LayoutParams(300, dp1 * 23)
        leftTextView.gravity = Gravity.CENTER_HORIZONTAL

        rightTextView.setTextColor(currentTextColor)
        rightTextView.textSize = textSize
        rightTextView.text = rightProgress.toString()
        //宽度写大一点，免得每次文字修改都测量
        rightTextView.layoutParams = LayoutParams(300, dp1 * 23)
        rightTextView.gravity = Gravity.CENTER_HORIZONTAL

        addView(leftTextView)
        addView(rightTextView)
    }

    /**
     * 初始化开始的进度和结束的进度
     */
    private fun initStartAndEndText() {
        startText.setTextColor(startAndEndTextColor)
        startText.textSize = textSize
        startText.text = startProgress.toString()
        val startLayout = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        startLayout.leftMargin = toggleIconSize / 2
        startText.layoutParams = startLayout

        endText.setTextColor(startAndEndTextColor)
        endText.textSize = textSize
        endText.text = endProgress.toString()
        val endLayout = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        endLayout.rightMargin = toggleIconSize / 2
        endLayout.gravity = Gravity.RIGHT
        endText.layoutParams = endLayout

        addView(startText)
        addView(endText)
    }

    fun setStartAndEnd(startProgress: Float, endProgress: Float) {
        this.startProgress = startProgress
        this.endProgress = endProgress
        startText.text = startProgress.toString()
        endText.text = endProgress.toString()
        postInvalidate()
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (ev != null) {
            dragHelper.shouldInterceptTouchEvent(ev)
        } else {
            super.onInterceptTouchEvent(ev)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            dragHelper.processTouchEvent(event)
            return true
        }
        return super.onTouchEvent(event)
    }

}
